define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'partner/upgrade/setting/index' + location.search,
                    add_url: 'partner/upgrade/setting/add',
                    edit_url: 'partner/upgrade/setting/edit',
                    del_url: 'partner/upgrade/setting/del',
                    multi_url: 'partner/upgrade/setting/multi',
                    import_url: 'partner/upgrade/setting/import',
                    table: 'partner_upgrade_setting',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'level.level_name', title: '对应等级名称', operate: 'LIKE'},
                        {field: 'type', title: __('Type'), searchList: {"1":__('Type 1'), "2":__('Type 2')}, formatter: Table.api.formatter.normal},
                        {field: 'amount', title: __('Amount')},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'reach_button',
                                    text: '达标明细',
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    icon: 'fa fa-check-square',
                                    url: function (row) {
                                        return Fast.api.fixurl('partner/upgrade/setting/settings?setting_id=' + row.id)
                                    },
                                    extend: "data-area='[\"60%\", \"80%\"]'",
                                },
                            ],
                            formatter: function(value, row, index){
                                var that = $.extend({}, this);
                                var table = $(that.table).clone(true);
                                if (row.type == 2){
                                    $(table).data("operate-reach_button", null);
                                }
                                that.table = table;
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        settings: function () {
            const option = {
                setup(){
                    const {ref,onMounted, nextTick, watch} = Vue;
                    const formLabelWidth = ref('140px')
                    const tableData = ref([])
                    const levels = ref([])
                    const dialogFormVisible = ref(false)
                    const levelId = ref('')
                    const amount = ref('0')
                    const dialogTitle = ref('增加达标明细')
                    const settingId = new URLSearchParams(location.search).get('setting_id') || 0
                    let levelName = ''

                    const params = {
                      'setting_id': 0,
                      'id': '0',
                      'level_id': '',
                      'level_name': '',
                      'amount': '0',
                      'is_del': '0',
                    }
                    const saveData = ref(params)
                    onMounted(()=>{
                        loadData()
                        Controller.api.bindevent();  
                    })
                    function loadData() {
                        $.ajax({
                            url: `partner/upgrade/setting/settings`,
                            type: 'get',
                            data: {
                              setting_id: settingId,
                            },
                            success: function (ret) {
                                tableData.value = ret['list']
                                levels.value = ret['levels']
                            }, error: function (e) {
                                Backend.api.toastr.error(e.message);
                            }
                        });
                    }
                    function handleChange(id) {
                      const levelObj = levels.value.find(item => item.id === id)
                      levelName = levelObj.level_name 
                    }
                    function handleAdd() {
                      params.setting_id = settingId
                      params.is_del = '0'
                      saveData.value = params
                      levelId.value = ''
                      amount.value = '0'
                      levelName = ''
                      dialogFormVisible.value = true
                    }
                    function handleEdit(setting) {
                      console.log('setting =>', setting)
                      levelId.value = setting['level_id'] * 1
                      amount.value = setting['amount']
                      levelName = setting['level_name']
                      setting['is_del'] = '0'
                      saveData.value = Object.assign({}, setting)
                      dialogFormVisible.value = true
                      dialogTitle.value = '修改达标明细'
                    }
                    function handleDel(setting) {
                      Layer.confirm('确定要删除此项吗？', {icon: 3, title:'删除提示'},
                          function(index){
                              layer.close(index); //关闭弹窗
                              setting['is_del'] = '1'
                              saveData.value = Object.assign({}, setting)
                              handleSave()
                          }
                      );
                    }
                    function handleSave() {
                      if (saveData.value['is_del'] !== '1' && levelId.value === '') {
                          Backend.api.toastr.error('未选择等级');
                          return
                      }
                      saveData.value['level_id'] = levelId.value
                      saveData.value['amount'] = amount.value
                      saveData.value['level_name'] = levelName
                      console.log('saveData =>', saveData.value)
                      $.ajax({
                          url: `partner/upgrade/setting/settingsave`,
                          type: 'post',
                          dataType: 'json',
                          data: saveData.value,
                          success: function (ret) {
                              if (ret.hasOwnProperty("code")) {
                                  var data = ret.hasOwnProperty("data") && ret.data != "" ? ret.data : "";
                                  if (ret.code === 1) {
                                      loadData() 
                                      dialogFormVisible.value = false
                                      if (saveData.value['is_del'] === '1') {
                                        Backend.api.toastr.success('删除成功');
                                      } else {
                                        Backend.api.toastr.success('保存成功');
                                      }
                                  } else {
                                      Backend.api.toastr.error(ret.msg);
                                  }
                              }
                          }, error: function (e) {
                              Backend.api.toastr.error(e.message);
                          }
                      });
                    }
                    return {
                      tableData,
                      levels,
                      levelId,
                      amount,
                      dialogTitle,
                      dialogFormVisible,
                      handleChange,
                      formLabelWidth,
                      loadData,
                      handleAdd,
                      handleEdit,
                      handleDel,
                      handleSave,
                    };
                }
                
            }
            createApp('settings', option)
        },
        
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
